package org.java.net.socket;

import java.io.BufferedReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.InputStreamReader;
import java.io.IOException;

public class Server2 {
	
	private BufferedReader reader;
	
	private ServerSocket server;
	
	private Socket socket;
	
	public Server2() {}
	
	void startServer()
	{
		try {
			server = new ServerSocket(4747);
			System.out.println("服务器套接字创建完毕");
			
			while(true)
			{
				System.out.println("等待客户机");
				
				socket = server.accept();
				System.out.println("完成客户机的连接");
				
				//获取socket输入流
				reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				
				getMessage();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println(e);
		}
	}
	
	void getMessage()
	{
		try 
		{
			while(true)
			{
				System.out.println("客户机：" + reader.readLine());
			}
		} 
		catch (Exception e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally
		{
			System.out.println("客户机中断连接");
			try
			{
				if(reader != null)
					reader.close();
				if(socket != null)
					socket.close();
			}
			catch(IOException ie)
			{}
		}
	}
	
	public static void main(String[] args)
	{
		Server2 server = new Server2();
		server.startServer();
	}

}
